package com.atguigu.security.config;

import com.atguigu.security.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: Administrator
 * @description:
 * @cteate 2021-06-08-21:19
 */

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据表单提交的用户名信息,查询User对象,并装配上角色 权限等信息
     * @param username 用户名参数
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        String sql = "select `id`,`login_acct` loginAcct,`user_pswd` userPswd,`user_name` userName,`email` from `t_admin` where `login_acct` = ?";

        // BeanPropertyRowMapper 可以将数据库查询结果封装为实体类对象
        List<Admin> adminList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Admin.class), username);
        // 取出封装好的admin对象
        Admin admin = adminList.get(0);

        // 把admin对象和角色 权限信息一起封装成为UserDetails

        // 存储角色权限对象的list
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        // 注意这一步用到了之前提过的角色和权限的区别
        authorities.add(new SimpleGrantedAuthority("ROLE_学徒"));
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        authorities.add(new SimpleGrantedAuthority("UPDATE"));

        String userPswd = admin.getUserPswd();
        // 这个user不是自建的类,是SpringSecurity中的一个类
        return new User(username,userPswd,authorities);
    }
}
